package com.codi.api.controller.assets;

import com.codi.base.spring.SpringContextHolder;
import com.codi.base.util.DateUtils;
import com.codi.base.util.MoneyUtils;
import com.codi.base.util.StringUtil;
import com.codi.bus.core.dao.CdUserShareDao;
import com.codi.bus.core.dao.ProfitDao;
import com.codi.bus.core.dao.UserDao;
import com.codi.bus.core.domain.InsidePortfolio;
import com.codi.bus.core.domain.Profit;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.resultModel.ApplyListResult;
import com.codi.bus.core.resultModel.AssetsPortfolioResult;
import com.codi.bus.core.resultModel.AssetsResult;
import com.codi.bus.core.resultModel.BaseResult;
import com.codi.bus.core.service.AssetsQueryService;
import com.codi.bus.core.service.MessageService;
import com.codi.bus.core.service.QueryService;
import com.codi.bus.core.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by asus on 2018/3/9.
 */
@Controller
@RestController
@RequestMapping("/assetsQuery")
@Slf4j
public class AssetsQueryController {
    @Autowired
    private AssetsQueryService assetsQueryService;

    @Autowired
    private QueryService queryService;

    @Autowired
    private ProfitRepairServiceImpl profitRepairService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    private ProfitDao profitDao;

    @Autowired
    private CdUserShareDao cdUserShareDao;


    @GetMapping("/sendMessage")
    public BaseResult sendMessage(String message) {
        messageService.sendMessageAllUser(message);
        return new BaseResult();
    }

    @GetMapping("all")
    public BaseResult queryAssets(Long userId) {
//        List<User> users = userDao.getAllUser();
//        int count = 0;
//        for (User user : users){
//            if (!Strings.isNullOrEmpty(user.getExternalClientId())){
//                AssetsResult assetsResult = assetsQueryService.queryAssets(user.getUserId());
//                count ++;
//                log.debug("计算完成");
//                log.debug("用户：{}，资产：{}",user.getUserName(),assetsResult.getTotalWorthValue());
//                log.debug("个数：{}",count);
//            }
//        }

        AssetsResult assetsResult = assetsQueryService.queryAssets(userId);
        //assetsQueryService.insertAssets(assetsResult,userId);
        return assetsResult;

    }


    @GetMapping("one")
    public BaseResult queryAssetsOne(Long userId) {
//        List<User> users = userDao.getAllUser();
//        int count = 0;
//        for (User user : users){
//            if (!Strings.isNullOrEmpty(user.getExternalClientId())){
//                AssetsResult assetsResult = assetsQueryService.queryAssets(user.getUserId());
//                count ++;
//                log.debug("计算完成");
//                log.debug("用户：{}，资产：{}",user.getUserName(),assetsResult.getTotalWorthValue());
//                log.debug("个数：{}",count);
//            }
//        }

        AssetsResult assetsResult = queryService.queryAssets(userId);
        //assetsQueryService.insertAssets(assetsResult,userId);
        return assetsResult;
    }

    @GetMapping("portfolio")
    public BaseResult queryPortfolio(Long userId) {
        AssetsPortfolioResult assetsPortfolioResult = new AssetsPortfolioResult();
        assetsPortfolioResult = queryService.queryPortfolioAssets(userId);
        return assetsPortfolioResult;
    }

    @GetMapping("apply")
    public BaseResult queryApply(Long userId) {


        ApplyListResult applyListResult = queryService.queryApplys(userId, 50, 1, 1, "1", true);
        //assetsQueryService.insertAssets(assetsResult,userId);
        return applyListResult;
    }

    @GetMapping("accumone")
    public BaseResult accum(Long userId) {
        queryService.queryAccumlateIncomeForProfit(userId);
        return new BaseResult();
    }

    @GetMapping("setClientId")
    public BaseResult setClientId() {
        queryService.setClient();
        return new BaseResult();
    }

    @GetMapping("dividendTest")
    public BaseResult dividendTest(Long userId, int i) {
        User user = userDao.getEntity(userId);
        assetsQueryService.dividendTest(user, i);
        return new BaseResult();
    }

    /**
     * 修复数据  一次性
     * @return
     */
    @GetMapping("profitRepair")
    public BaseResult profitRepair(String dateOne, int two, String dateThree, int four) {
        profitRepairService.execProfit(dateOne, two, dateThree, four);
        return new BaseResult();
    }

    /**
     * 修复累计收益
     *
     * @return
     */
    @GetMapping("accumall")
    public BaseResult accumAll() {
        List<User> users = userDao.getAllUser();
        for (User user : users) {
            if (user == null || StringUtil.isEmpty(user.getExternalClientId())) {
                continue;
            }
            queryService.queryAccumlateIncomeForProfit(user.getUserId());
        }
        return new BaseResult();
    }

    @GetMapping("profit")
    public void profit() {
        Date date = new Date();
        date = DateUtils.addDay(date, -25);
        BigDecimal day = new BigDecimal(726.6100);
        BigDecimal all = new BigDecimal(5726.6100);
        for (int i = 0; i < 400; i++) {
            day = MoneyUtils.add(day, new BigDecimal(-0.5));
            all = MoneyUtils.add(all, new BigDecimal(-1));
            date = DateUtils.addDay(date, -1);
            Profit profit = new Profit();
            profit.setUserId(4304);
            profit.setTradeAcco("ZHLC000000000926");
            profit.setClientId("6278");
            profit.setFundCode("200010");
            profit.setDateTime(DateUtils.formatDateTime(date));
            profit.setNetValue(BigDecimal.valueOf(1.4363));
            profit.setPreNetValue(BigDecimal.valueOf(1.4363));
            profit.setShares(BigDecimal.valueOf(18452.3700));
            profit.setProfitValue(day);
            profit.setAccumulateProfitValue(all);
            profit.setCreateTime(DateUtils.formatDateTime(DateUtils.addDay(date, 1)));
            profitDao.insert(profit);
            profit.setFundCode("200008");
            profitDao.insert(profit);
            profit.setTradeAcco("0923");
            profitDao.insert(profit);
        }
    }

    @GetMapping("inside/portfolio")
    public void queryInsidePortfolio(Boolean flag) {
        List<User> users = userDao.getAllUser();
        for (User user : users) {
            if (user.getExternalClientId() != null) {
                assetsQueryService.getInsidePortfolio(user, flag);
            }
        }
    }

    @GetMapping("inside/portfolioAssets")
    public void queryInsidePortfolioAssets() {
        List<InsidePortfolio> insidePortfolios = assetsQueryService.getMobile();

        for (InsidePortfolio insidePortfolio : insidePortfolios) {
            User user = userDao.getEntityByMobile(insidePortfolio.getUserMobile());
            if (user.getExternalClientId() != null) {
                assetsQueryService.getPortfolioAssets(user);
            }
        }
    }

    @GetMapping("inside/portfolioTradeAccount")
    public void queryPortfolioTradeAccount() {
        List<InsidePortfolio> insidePortfolios = assetsQueryService.getMobile();

        for (InsidePortfolio insidePortfolio : insidePortfolios) {
            User user = userDao.getEntityByMobile(insidePortfolio.getUserMobile());
            if (user.getExternalClientId() != null) {
                assetsQueryService.getPortfolioTradeAccount(user);
            }
        }
    }

    @GetMapping("inside/initDividents")
    public void initDividents() {
        List<User> users = userDao.getAllUser();
        for (User user : users) {
            if (StringUtils.isBlank(user.getExternalClientId())) {
                continue;
            }
            assetsQueryService.initDividents(user);
        }
    }

    @GetMapping("execute")
    public void executeInternal() throws Exception {
        log.info("refresh AssetsJob ");

        //用户份额  目前 全量更新  调恒生
        LocaldataUserShareService localdataUserShareService = SpringContextHolder.getBean(LocaldataUserShareService.class);
        localdataUserShareService.init();
        //分红  每日全量更新  调恒生
        LocaldataDividentsService localdataDividentsService = SpringContextHolder.getBean(LocaldataDividentsService.class);
        localdataDividentsService.addDividents();
        // 日收益  根据份额 不调恒生
        LocaldataProfitService localdataProfitService = SpringContextHolder.getBean(LocaldataProfitService.class);
        localdataProfitService.execProfit();
        //更新交易申请   调恒生
        LocaldataTradeOrderService localdataTradeOrderService = SpringContextHolder.getBean(LocaldataTradeOrderService.class);
        localdataTradeOrderService.updateOrder(false);
        //业务净收入  每日更新  不会调恒生   根据订单和份额
        log.info("业务收入 ");

        BusinessIncomeService businessIncomeService = SpringContextHolder.getBean(BusinessIncomeService.class);
        businessIncomeService.exec();
    }


    @GetMapping("executeDividend")
    public void executeDividend() throws JobExecutionException {
        log.info("refresh AssetsJob ");

        //分红  每日全量更新  调恒生
        LocaldataDividentsService localdataDividentsService = SpringContextHolder.getBean(LocaldataDividentsService.class);
        localdataDividentsService.addDividents();
    }

    /**
     * 根据 收益日期删
     *
     * @param time
     */
    @GetMapping("deleteProfit")
    public void deleteProfit(String time) {
//"2018-07-10"
        profitDao.deleteByDateTime(time);
    }

    /**
     * 根据创建日期删
     *
     * @param time
     */

    @GetMapping("deleteProfitByCreateTime")
    public void deleteProfitByCreateTime(String time) {
//"2018-07-13"
        profitDao.deleteByCreateTime(time);
    }

    /**
     * 0->1
     * @param time
     */
    @GetMapping("updateShareState")
    public void updateShareState(String time) {
//20180711
        cdUserShareDao.updateShareToday(time);
    }

    /**
     * 1->0
     *
     * @param time
     */
    @GetMapping("changeShareToday")
    public void changeShareToday(String time) {
//20180711
        cdUserShareDao.changeShareToday(time);
    }
}
